﻿using Appliaction.Dto.Inv;
using Domain.Entitys.Inv;
using Domain.IRepositorys.Inv;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace EFCore.Repositorys.Inv
{
    public class Inv_StockRepository : IInv_StockRepository
    {
        private readonly MyDbContext myDbContext;

        public Inv_StockRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }
        /// <summary>
        /// 获取库存数量
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="por_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Getinv_stock(string weahouse_code,string por_code)
        {
            // 使用异步版本
                bool exists = await myDbContext.inv_stock
                .Where(s => s.Del_Flag == '0'
                            && s.Warehouse_Code == weahouse_code
                            && s.pro_code == por_code)
                .AnyAsync();

            if (exists)
            {
                decimal total = await myDbContext.inv_stock
                    .Where(s => s.Del_Flag == '0'
                                && s.Warehouse_Code == weahouse_code
                            
                                && s.pro_code == por_code)
                    .SumAsync(s => s.stock_numder);

                return (int)Math.Round(total);
            }
            return 0;
        }




        /// <summary>
        /// 根据仓库编号查询去库存筛选产品
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<inv_stock>> Get_Select_weahouse_code(string weahouse_code,int currentPage, int pageSize)
        {
           var result = await myDbContext.inv_stock.Where(s => s.Del_Flag == '0' && s.Warehouse_Code == weahouse_code).ToListAsync();

                            
            return result.Skip((currentPage-1)*pageSize).Take(pageSize).ToList();
        }
        /// <summary>
        /// 查询编码查询库存数量总数
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> Get_Select_Weahouse_code_Count(string weahouse_code)
        {
            var query= myDbContext.inv_stock.Where(e => e.Warehouse_Code == weahouse_code).CountAsync();
            return query;
        }

   

        /// 盘亏--修正库存
        /// </summary>
        /// <param name="invStockDtos">需要更新的库存列表</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> Update_inv_Stock_numder(List<Inv_Stock_numderUpdateDto> invStockDtos)
        {
            if (invStockDtos == null || !invStockDtos.Any())
                throw new ArgumentException("库存更新数据不能为空");

            // 1. 构建临时表数据（转换为 SQL 可识别的字符串）
            var keys = invStockDtos
                .Select(dto => new {
                    dto.Warehouse_Code,
                    dto.Zone_Code,
                    dto.Location_Code,
                    dto.pro_code
                })
                .Distinct()
                .ToList();

            // 2. 构建 SQL 查询语句（适用于 SQL Server）
            var sqlValues = string.Join(",",
                keys.Select(k => $@"('{k.Warehouse_Code}', '{k.Zone_Code}', '{k.Location_Code}', '{k.pro_code}')"));

            var sql = $@"
        SELECT * FROM inv_stock
        WHERE EXISTS (
            SELECT 1 FROM (VALUES {sqlValues}) AS Keys(Warehouse_Code, Zone_Code, Location_Code, pro_code)
            WHERE inv_stock.Warehouse_Code = Keys.Warehouse_Code
              AND inv_stock.Zone_Code = Keys.Zone_Code
              AND inv_stock.Location_Code = Keys.Location_Code
              AND inv_stock.pro_code = Keys.pro_code
        )";

            // 3. 执行 SQL 查询获取现有记录
            var existingRecords = await myDbContext.inv_stock
                .FromSqlRaw(sql)
                .ToDictionaryAsync(s => new {
                    s.Warehouse_Code,
                    s.Zone_Code,
                    s.Location_Code,
                    s.pro_code
                });

            // 4. 更新内存中的实体
            var recordsToUpdate = new List<inv_stock>();
            var missingRecords = new List<string>();

            foreach (var dto in invStockDtos)
            {
                var key = new
                {
                    dto.Warehouse_Code,
                    dto.Zone_Code,
                    dto.Location_Code,
                    dto.pro_code
                };

                if (existingRecords.TryGetValue(key, out var record))
                {
                    record.stock_numder = dto.stock_numder;
                    recordsToUpdate.Add(record);
                }
                else
                {
                    missingRecords.Add($"仓库:{dto.Warehouse_Code}, 产品:{dto.pro_code}, 库区:{dto.Zone_Code}, 库位:{dto.Location_Code}");
                }
            }

            // 5. 处理缺失记录
            if (missingRecords.Any())
            {
                Console.WriteLine("以下库存记录不存在，无法更新：\n" + string.Join("\n", missingRecords));
            }

            // 6. 批量保存更新
            if (!recordsToUpdate.Any()) return 0;

            const int batchSize = 500;
            int totalUpdated = 0;

            for (int i = 0; i < recordsToUpdate.Count; i += batchSize)
            {
                var batch = recordsToUpdate.Skip(i).Take(batchSize).ToList();

                using var transaction = await myDbContext.Database.BeginTransactionAsync();
                try
                {
                    myDbContext.inv_stock.UpdateRange(batch);
                    int updated = await myDbContext.SaveChangesAsync();
                    await transaction.CommitAsync();
                    totalUpdated += updated;
                }
                catch (Exception ex)
                {
                    await transaction.RollbackAsync();
                    Console.WriteLine($"事务回滚，错误：{ex.Message}");
                    throw;
                }
            }

            return totalUpdated;
        }


        /// <summary>
        /// 添加查询条件,获取库存数量--添加二个条件产品编码、字典编码
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="pro_code"></param>
        /// <param name="dict_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<int> Get_Select__stock_Count(string weahouse_code, string pro_code, int dict_code)
        {
            var query = myDbContext.inv_stock.AsQueryable();

            query = query.Where(x => x.Del_Flag == '0');

            if (!string.IsNullOrEmpty(weahouse_code))
            {
                query = query.Where(x => x.Warehouse_Code == weahouse_code);
            }

            // 条件1: 入库类型筛选（如果提供了）
            if (!string.IsNullOrEmpty(pro_code))
            {
                query = query.Where(x => x.pro_code == pro_code);
            }

            // 条件2: 关键字搜索（如果提供了）
            if (dict_code > 0) { 
                query = query.Where(x => x.dict_code == dict_code);
            }

            // 统计总数
            return query.CountAsync();
        }
        /// <summary>
        ///  添加查询条件,获取库存数量--添加二个条件产品编码、字典编码
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="pro_code"></param>
        /// <param name="dict_code"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<inv_stock>> Get_Select_stock_All(string weahouse_code, string pro_code, int dict_code, int currentPage, int pageSize)
        {
            var query = myDbContext.inv_stock
                           .Where(x => x.Del_Flag == '0');

            if (!string.IsNullOrEmpty(weahouse_code))
                query = query.Where(x => x.Warehouse_Code == weahouse_code);

            if (!string.IsNullOrEmpty(pro_code))
                query = query.Where(x => x.pro_code == pro_code);

            if (dict_code > 0)
                query = query.Where(x => x.dict_code == dict_code);

            // 分页：先排序再跳过/取数
            return await query
                         .OrderBy(x => x.pro_code)           // 可根据需要调整排序字段
                         .Skip((currentPage - 1) * pageSize)
                         .Take(pageSize)
                         .ToListAsync();
        }
        /// <summary>
        /// 修改库存数量
        /// </summary>
        /// <param name="Stock_UpdateTrfDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> stock_Update_kc(List<Stock_UpdateTrfDto> updateList)
        {

            if (updateList == null || !updateList.Any())
                return 0;

            int affectedRows = 0;

            using (var transaction = await myDbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    // 获取去重后的库存键
                    var stockKeys = updateList
                        .Select(u => new { u.Warehouse_Code, u.Zone_Code, u.Location_Code, u.pro_code })
                        .Distinct()
                        .ToList();

                    // 使用 JOIN 代替复杂的 Any 条件
                    var allStocks = await myDbContext.inv_stock.AsNoTracking().ToListAsync();

                    var existingStocks = allStocks
                        .Join(
                            stockKeys,
                            s => new
                            {
                                s.Warehouse_Code,
                                s.Zone_Code,
                                s.Location_Code,
                                s.pro_code
                            },
                            k => new
                            {
                                k.Warehouse_Code,
                                k.Zone_Code,
                                k.Location_Code,
                                k.pro_code
                            },
                            (stock, key) => stock
                        )
                        .ToList();

                    // 创建字典便于快速查找
                    var stockDict = existingStocks.ToDictionary(s =>
                        $"{s.Warehouse_Code}|{s.Zone_Code}|{s.Location_Code}|{s.pro_code}");

                    // 后续处理保持不变...
                    foreach (var updateItem in updateList)
                    {
                        var key = $"{updateItem.Warehouse_Code}|{updateItem.Zone_Code}|{updateItem.Location_Code}|{updateItem.pro_code}";

                        if (stockDict.TryGetValue(key, out var existingStock))
                        {
                            existingStock.stock_numder += updateItem.stock_numder;
                            myDbContext.inv_stock.Update(existingStock);
                        }
                        else
                        {

                            string vendorCode = updateItem.Vendor_Code;
                            string vendorName = updateItem.Vendor_Name;



                         

                            // 只有在前端没有传入的情况下，才去查数据库
                            if (vendorCode==null || vendorName==null)
                            {
                                var vendorInfo = existingStocks.FirstOrDefault(s => s.pro_code == updateItem.pro_code);

                                if (vendorInfo == null)
                                {
                                    vendorInfo = await myDbContext.inv_stock
                                        .FirstOrDefaultAsync(s => s.pro_code == updateItem.pro_code &&
                                                                  s.stock_entry_no == updateItem.stock_entry_no_pd);
                                }

                                if (vendorInfo != null)
                                {
                                    vendorCode = vendorInfo.Vendor_Code;
                                    vendorName = vendorInfo.Vendor_Name;
                                }
                            }

                            // 检查供应商信息是否存在
                            //var vendorInfo = existingStocks.FirstOrDefault(s => s.pro_code == updateItem.pro_code);

                            //if (vendorInfo == null)
                            //{
                            //    // 如果供应商信息不存在，则查询数据库
                            //    vendorInfo = await myDbContext.inv_stock
                            //        .FirstOrDefaultAsync(s => s.pro_code == updateItem.pro_code && s.stock_entry_no== updateItem.stock_entry_no_pd);
                            //}
                           
                                // 创建新库存记录
                                var newStock = new inv_stock
                                {
                                    stock_name = updateItem.stock_name,
                                    pro_code = updateItem.pro_code,
                                    pro_brand = updateItem.pro_brand,
                                    dict_code = updateItem.dict_code,
                                    stock_model = updateItem.stock_model,
                                    Pro_attribute_id = updateItem.Pro_attribute_id,
                                    pro_cost_price = updateItem.pro_cost_price,
                                    Pro_sale_price = updateItem.Pro_sale_price,
                                    stock_numder = updateItem.stock_numder,
                                    stock_entry_no = updateItem.stock_entry_no,
                                    Vendor_Code = vendorCode,
                                    Vendor_Name = vendorName,
                                    Warehouse_Code = updateItem.Warehouse_Code,
                                    Warehouse_Name = updateItem.Warehouse_Name,
                                    Zone_Code = updateItem.Zone_Code,
                                    Zone_Name = updateItem.Zone_Name,
                                    Location_Code = updateItem.Location_Code,
                                    Location_Name = updateItem.Location_Name,
                                    create_by=updateItem.create_by,
                                    Create_Time=updateItem.Create_Time,

                                    Del_Flag = '0'
                                };



                                await myDbContext.inv_stock.AddAsync(newStock);

                                // 添加到字典避免同批次重复创建
                                stockDict.Add(key, newStock);
                            }

                            //myDbContext.inv_stock.Add(newStock);
                        
                    }

                    affectedRows = await myDbContext.SaveChangesAsync();
                    await transaction.CommitAsync();
                }
                catch (Exception ex)
                {
                    await transaction.RollbackAsync();
                    Console.WriteLine($"Error updating stock: {ex.Message}");
                    throw;
                }
            }

            return affectedRows;
        }

        public async Task<int> Getinv_stock_XQ(string weahouse_code, string por_code, string stock_entry_no)
        {
            // 使用异步版本
            bool exists = await myDbContext.inv_stock
            .Where(s => s.Del_Flag == '0'
                        && s.Warehouse_Code == weahouse_code
                        && s.pro_code == por_code
                        && s.stock_entry_no == stock_entry_no)
            .AnyAsync();

            if (exists)
            {
                decimal total = await myDbContext.inv_stock
                    .Where(s => s.Del_Flag == '0'
                                && s.Warehouse_Code == weahouse_code

                                && s.pro_code == por_code)
                    .SumAsync(s => s.stock_numder);

                return (int)Math.Round(total);
            }
            return 0;
        }
        

        /// <summary>
        /// 查询数量--总数量
        /// </summary>
        /// <param name="Pro_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Get_inv_stock_totalnumber(string Pro_code)
        {
            if (string.IsNullOrEmpty(Pro_code))
            {
                throw new ArgumentException("产品编码不能为空", nameof(Pro_code));
            }

            // 查询数据库，获取所有匹配的产品库存记录
            var totalStock = await myDbContext.inv_stock
                .Where(s => s.pro_code == Pro_code && s.Del_Flag != '1') // 确保只计算未删除的记录
                .SumAsync(s => s.stock_numder); // 计算总库存数量

            return (int)totalStock; // 返回总库存数量
        }
        /// <summary>
        /// 结构入库编号,产品编号,仓库编号去查询这个产品在的库位和库区
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="pro_code"></param>
        /// <param name="stock_entry_no"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<inv_stock>> Get_Select_stock_All_By_Pro_Code(string weahouse_code, string pro_code, string stock_entry_no)
        {
            // 构建查询：筛选出匹配仓库编码、产品编码和入库单号的记录。
            var query = myDbContext.inv_stock.AsQueryable();

            if (!string.IsNullOrEmpty(weahouse_code))
            {
                query = query.Where(s => s.Warehouse_Code == weahouse_code);
            }

            if (!string.IsNullOrEmpty(pro_code))
            {
                query = query.Where(s => s.pro_code == pro_code);
            }

            if (!string.IsNullOrEmpty(stock_entry_no))
            {
                query = query.Where(s => s.stock_entry_no == stock_entry_no);
            }

            // 执行查询并返回结果。
            return await query.ToListAsync();
        }
        /// <summary>
        /// 其他出库单减少库存
        /// </summary>
        /// <param name="inv_Stocks"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Stock_update(List<inv_stock> inv_Stocks)
        {

            using (var transaction = myDbContext.Database.BeginTransaction())
            {
                try
                {
                    int affectedRows = 0;

                    foreach (var stockUpdate in inv_Stocks)
                    {
                        // 查询匹配的库存记录
                        var existingStock = await myDbContext.inv_stock
                            .Where(s => s.pro_code == stockUpdate.pro_code
                                     && s.Warehouse_Code == stockUpdate.Warehouse_Code
                                     && s.Zone_Code == stockUpdate.Zone_Code
                                     && s.Location_Code == stockUpdate.Location_Code
                                     && s.stock_entry_no == stockUpdate.stock_entry_no)
                            .FirstOrDefaultAsync();

                        if (existingStock == null)
                        {
                            throw new Exception($"库存记录不存在：产品 {stockUpdate.pro_code}，仓库 {stockUpdate.Warehouse_Code}，库位 {stockUpdate.Location_Code}");
                        }

                        if (existingStock.stock_numder < stockUpdate.stock_numder)
                        {
                            throw new Exception($"库存不足：产品 {stockUpdate.pro_code}，仓库 {stockUpdate.Warehouse_Code}，当前库存 {existingStock.stock_numder}，需要减少 {stockUpdate.stock_numder}");
                        }

                        // 减少库存数量
                        existingStock.stock_numder -= stockUpdate.stock_numder;

                        // 如果库存减到0以下，设置为0（可选）
                        if (existingStock.stock_numder < 0)
                        {
                            existingStock.stock_numder = 0;
                        }

                        // 更新记录
                        myDbContext.inv_stock.Update(existingStock);
                        affectedRows += await myDbContext.SaveChangesAsync();
                    }

                    transaction.Commit();
                    return affectedRows;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    // 记录日志
                   
                    throw; // 重新抛出异常
                }
            }
        }
        /// <summary>
        /// 查询仓库库存
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="Vendor_Code"></param>
        /// <param name="pro_code"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<inv_stock>> Get_Select_stock(string weahouse_code, string zone_code, string location_code, string Vendor_Code, string pro_code, int currentPage, int pageSize)
        {
           IQueryable<inv_stock> inv_Stocks=myDbContext.inv_stock.AsQueryable();
            if (!string.IsNullOrEmpty(weahouse_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Warehouse_Code == weahouse_code);
            }
            if (!string.IsNullOrEmpty(zone_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Zone_Code == zone_code);
            }
            if (!string.IsNullOrEmpty(location_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Location_Code == location_code);
            }
            if (!string.IsNullOrEmpty(Vendor_Code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Vendor_Code == Vendor_Code);
            }
            if (!string.IsNullOrEmpty(pro_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.pro_code == pro_code);
            }
            inv_Stocks = inv_Stocks.Where(x => x.Del_Flag == '0');

            // 分页：先排序再跳过/取数
            return await inv_Stocks
                         .OrderBy(x => x.pro_code)           // 可根据需要调整排序字段
                         .Skip((currentPage - 1) * pageSize)
                         .Take(pageSize)
                         .ToListAsync();

        }
        /// <summary>
        /// 查询仓库库存总数
        /// </summary>
        /// <param name="weahouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="Vendor_Code"></param>
        /// <param name="pro_code"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public Task<int> Get_Select_stock_count(string weahouse_code, string zone_code, string location_code, string Vendor_Code, string pro_code)
        {
            var inv_Stocks = myDbContext.inv_stock.AsQueryable();
            inv_Stocks = inv_Stocks.Where(x => x.Del_Flag == '0');
            if (!string.IsNullOrEmpty(weahouse_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Warehouse_Code == weahouse_code);
            }
            if (!string.IsNullOrEmpty(zone_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Zone_Code == zone_code);
            }
            if (!string.IsNullOrEmpty(location_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Location_Code == location_code);
            }
            if (!string.IsNullOrEmpty(Vendor_Code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Vendor_Code == Vendor_Code);
            }
            if (!string.IsNullOrEmpty(pro_code))
            {
                inv_Stocks = inv_Stocks.Where(x => x.Vendor_Code == Vendor_Code);
            }
            return inv_Stocks.CountAsync();
        }
        /// <summary>
        /// 选择期初入库的时候--有动态的展示库存数量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="pro_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<decimal> int_stock_numder(string warehouse_code, string zone_code, string location_code, string pro_code)
        {
            var query=await myDbContext.inv_stock.FirstOrDefaultAsync(s => s.Del_Flag == '0'&& s.Warehouse_Code == warehouse_code && s.Zone_Code == zone_code && s.Location_Code == location_code && s.pro_code == pro_code);
             if (query == null)
            {
                return 0;
            }
            return query.stock_numder;
        }

        /// <summary>
        /// 修改库存不合格数量
        /// </summary>
        /// <param name="prodInfo_totnum_uqual"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /*public async Task<int> stock_Update_stockUnqualified_numder(List<Inv_StockUpdateDto> prodInfo_totnum_uqual)
        {
            if (prodInfo_totnum_uqual == null || !prodInfo_totnum_uqual.Any())
                return 0;

            // 使用字典来合并相同产品的不合格数量
            var unqualifiedDict = new Dictionary<string, decimal>();

            // 提取 (Pro_code, Warehouse_code) 组合，并去重
            var keys = prodInfo_totnum_uqual
                .Select(p => new { p.Pro_code, p.Warehouse_code, p.stock_entry_no })
                .Distinct()
                .ToList();

            // 构建查询条件：Del_Flag = '0' 且匹配 (Pro_code, Warehouse_code)
            var query = myDbContext.inv_stock
                .Where(x => x.Del_Flag == '0' && x.stock_entry_no == keys.First().stock_entry_no);

            foreach (var key in keys)
            {
                // 构建每个 key 的条件
                var proCode = key.Pro_code;
                var warehouseCode = key.Warehouse_code;
                var stock_entry_no = key.stock_entry_no;

                query = query.Union(myDbContext.inv_stock
                    .Where(x => x.pro_code == proCode && x.Warehouse_Code == warehouseCode && x.stock_entry_no == stock_entry_no));
            }

            var existingStocks = await query.ToListAsync();

            // 初始化字典：将现有库存的不合格数量放入字典
            foreach (var stock in existingStocks)
            {
                var key = $"{stock.pro_code}_{stock.Warehouse_Code}_{stock.stock_entry_no}";
                unqualifiedDict[key] = stock.stock_unqualified_numder;
            }

            // 合并不合格数量（累加传入的数据）
            foreach (var item in prodInfo_totnum_uqual)
            {
                var key = $"{item.Pro_code}_{item.Warehouse_code}_{item.stock_entry_no}";
                if (unqualifiedDict.ContainsKey(key))
                {
                    unqualifiedDict[key] += item.prodInfo_totnum_uqual; // 累加
                }
                else
                {
                    unqualifiedDict[key] = item.prodInfo_totnum_uqual;
                }
            }

            // 开始事务
            await using var transaction = await myDbContext.Database.BeginTransactionAsync();

            try
            {
                foreach (var kvp in unqualifiedDict)
                {
                    var parts = kvp.Key.Split('_');
                    var proCode = parts[0];
                    var warehouseCode = parts[1];
                    var stock_entry_no = parts[2];
                    var totalUnqualified = kvp.Value;

                    // 查询库存记录
                    var stock = await myDbContext.inv_stock
                        .FirstOrDefaultAsync(s =>
                            s.pro_code == proCode &&
                            s.Warehouse_Code == warehouseCode &&
                            s.stock_entry_no == stock_entry_no &&
                            s.Del_Flag == '0');

                    if (stock != null)
                    {
                        // 累加不合格数量
                        stock.stock_unqualified_numder += totalUnqualified;
                        myDbContext.inv_stock.Update(stock);
                    }
                }

                // 保存更改
                await myDbContext.SaveChangesAsync();
                await transaction.CommitAsync();
            }
            catch (Exception ex)
            {
                // 出错回滚事务
                await transaction.RollbackAsync();
                throw new Exception("更新库存不合格数量失败", ex);
            }

            return unqualifiedDict.Count;
        }*/
    }
}

